import heapq


class P():
    def __init__(self, k, v):
        self.k = k
        self.v = v

    def __lt__(self, other):
        if self.v < other.v:
            return True
        elif self.v > other.v:
            return False
        else:
            for i in range(min(len(self.k), len(other.k))):
                if ord(self.k[i]) > ord(other.k[i]):
                    return False
                elif ord(self.k[i]) < ord(other.k[i]):
                    return True
            if len(self.k) > len(other.k):
                return True

    def p(self):
        return self.k


def topKFrequent(words, k):
    table = {}
    for word in words:
        if word in table:
            table[word] += 1
        else:
            table[word] = 1
    heap = []
    heapq.heapify(heap)
    for key, v in table.items():
        temp = P(key, v)
        heapq.heappush(heap, temp)
        if len(heap) > k:
            heapq.heappop(heap)
    res = []
    while len(heap) > 0:
        temp = heapq.heappop(heap)
        res.append(temp.p())
    res.reverse()
    return res


words = ['i', 'i', 'i', 'you', 'you', 'me', 'love', 'love', 'love', 'i']
print(topKFrequent(words, 2))
